import { defineStore } from 'pinia';
import { contestApi } from '../api/services.js';

export const useContestStore = defineStore('contest', {
  state: () => ({
    contests: [],
    currentContest: null,
    loading: false,
    pagination: {
      page: 1,
      pageSize: 10,
      total: 0
    }
  }),

  getters: {
    activeContests: (state) => state.contests.filter(contest => contest.status === 'active'),
    upcomingContests: (state) => state.contests.filter(contest => contest.status === 'upcoming'),
    endedContests: (state) => state.contests.filter(contest => contest.status === 'ended')
  },

  actions: {
    /**
     * 获取竞赛列表
     * @param {Object} params - 查询参数
     * @returns {Promise<Object>} 竞赛列表数据
     */
    async fetchContests(params = {}) {
      this.loading = true;
      try {
        const contestData = await contestApi.getContests(params);
        console.log(contestData, 111);
        
        // 确保 contests 始终是数组
        let contestsArray = [];
        if (contestData.data && Array.isArray(contestData.data.contests)) {
          contestsArray = contestData.data.contests;
        } else if (contestData.data && Array.isArray(contestData.data)) {
          contestsArray = contestData.data;
        } else if (Array.isArray(contestData)) {
          contestsArray = contestData;
        }
        
        this.contests = contestsArray;
        
        // 更新分页信息
        if (contestData.pagination) {
          this.pagination = contestData.pagination;
        }
        
        return contestData;
      } catch (error) {
        console.error('获取竞赛列表失败:', error);
        this.contests = [];
        throw error;
      } finally {
        this.loading = false;
      }
    },

    /**
     * 获取单个竞赛详情
     * @param {number} id - 竞赛ID
     * @returns {Promise<Object>} 竞赛详情
     */
    async fetchContestById(id) {
      this.loading = true;
      try {
        const contestDetail = await contestApi.getContestDetail(id);
        console.log('API返回的原始数据:', contestDetail, 55555555555555);
        
        // 确保isJoined字段存在，如果API没有返回则默认为false
        if (contestDetail && typeof contestDetail.isJoined === 'undefined') {
          contestDetail.isJoined = false;
        }
        
        this.currentContest = contestDetail;
        
        console.log('=== fetchContestById 调试信息 ===');
        console.log('API返回的原始数据:', contestDetail);
        console.log('isJoined字段值:', contestDetail?.isJoined);
        console.log('isJoined字段类型:', typeof contestDetail?.isJoined);
        console.log('==============================');
        
        return contestDetail;
      } catch (error) {
        console.error('获取竞赛详情失败:', error);
        this.currentContest = null;
        throw error;
      } finally {
        this.loading = false;
      }
    },

    /**
     * 参加竞赛
     * @param {number} contestId - 竞赛ID
     * @returns {Promise<Object>} 参加结果
     */
    async joinContest(contestId) {
      try {
        const result = await contestApi.joinContest(contestId);
        
        // 无论是新参与还是已经参与，都需要确保isJoined状态为true
        const contest = this.contests.find(c => c.id === contestId);
        if (contest) {
          // 只有在新参与时才增加参与人数
          if (result.status !== 'already_joined') {
            contest.participants = (contest.participants || 0) + 1;
          }
          contest.isJoined = true;
        }
        
        // 更新当前竞赛详情
        if (this.currentContest && this.currentContest.id === contestId) {
          // 只有在新参与时才增加参与人数
          if (result.status !== 'already_joined') {
            this.currentContest.participants = (this.currentContest.participants || 0) + 1;
          }
          this.currentContest.isJoined = true;
        }
        
        return result;
      } catch (error) {
        console.error('参加竞赛失败:', error);
        throw error;
      }
    },

    /**
     * 退出竞赛
     * @param {number} contestId - 竞赛ID
     * @returns {Promise<boolean>} 是否退出成功
     */
    async leaveContest(contestId) {
      try {
        const result = await contestApi.leaveContest(contestId);
        
        // 更新本地竞赛数据
        const contest = this.contests.find(c => c.id === contestId);
        if (contest) {
          contest.participants = Math.max((contest.participants || 1) - 1, 0);
          contest.isJoined = false;
        }
        
        // 更新当前竞赛详情
        if (this.currentContest && this.currentContest.id === contestId) {
          this.currentContest.participants = Math.max((this.currentContest.participants || 1) - 1, 0);
          this.currentContest.isJoined = false;
        }
        
        return true;
      } catch (error) {
        console.error('退出竞赛失败:', error);
        return false;
      }
    },

    /**
     * 提交竞赛作品
     * @param {number} contestId - 竞赛ID
     * @param {Object} workData - 作品数据
     * @param {File} file - 作品文件
     * @returns {Promise<Object>} 提交结果
     */
    async submitWork(contestId, workData, file) {
      try {
        const formData = new FormData();
        formData.append('title', workData.title);
        formData.append('description', workData.description);
        formData.append('file', file);
        
        const result = await contestApi.submitWork(contestId, formData);
        return result;
      } catch (error) {
        console.error('提交作品失败:', error);
        throw error;
      }
    },

    /**
     * 获取竞赛作品列表
     * @param {number} contestId - 竞赛ID
     * @param {Object} params - 查询参数
     * @returns {Promise<Object>} 作品列表
     */
    async getContestWorks(contestId, params = {}) {
      try {
        const worksData = await contestApi.getContestWorks(contestId, params);
        return worksData;
      } catch (error) {
        console.error('获取竞赛作品失败:', error);
        throw error;
      }
    },

    /**
     * 为竞赛作品投票
     * @param {number} workId - 作品ID
     * @returns {Promise<Object>} 投票结果
     */
    async voteWork(workId) {
      try {
        const result = await contestApi.voteWork(workId);
        return result;
      } catch (error) {
        console.error('投票失败:', error);
        throw error;
      }
    },

    /**
     * 获取我参加的竞赛
     * @param {Object} params - 查询参数
     * @returns {Promise<Object>} 我的竞赛列表
     */
    async getMyContests(params = {}) {
      try {
        const contestData = await contestApi.getMyContests(params);
        return contestData;
      } catch (error) {
        console.error('获取我的竞赛失败:', error);
        throw error;
      }
    }
  }
});